public class HashBuck2<K,V> {
    static class Node<K,V> {
        public K key;
        public V val;
        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
        public Node<K,V> next;
    }
    public Node<K,V>[] array = new Node[10];

    public int useSize;

    public static final double LOAD_FACTOR = 0.75;

    public void push(K key, V val) {

        Node<K,V> node = new Node<>(key,val);

        //找位置
        int hash = key.hashCode();//hashCode：给一个哈希值
        int index = hash % array.length;
        Node<K,V> cur = array[index];
        /*//查看是否位置为空
        if (cur == null) {
            array[index] = node;
            useSize++;
            return;
        }*/
        //循环
        while (cur != null) {
            if (cur.key.equals(key)) {
                cur.key = key;
            }
            cur = cur.next;
        }
        //头插法
        node.next = array[index];
        array[index] = node;
        useSize++;

        //重新哈希
        if (doLoadFactor() >= 0.75) {
            //负载因子过大，重新哈希（重新排列）
            reSize();
        }
    }
    private void reSize() {

        //重新写一个数组
        HashBuck2.Node<K,V>[] newArray = new Node[2*array.length];

        //重新哈希
        for (int i = 0; i < array.length; i++) {
            Node node = array[i];
            while (node != null) {

                int hash = node.key.hashCode();
                int index = hash % array.length;
                //1.判断是否是第一个插入
                if (newArray[index] == null) {
                    newArray[index] = node;
                    break;
                }
                //2.不是第一个插入则头插法,并插入新数组
                Node nodeNext = node.next;//记录node的下一个位置
                node.next = newArray[index];
                newArray[index] = node;

                node = nodeNext;
            }
        }

        //数据传到原数组 array
        array = newArray;
    }
    private double doLoadFactor() {
        return useSize*1.0/array.length;
    }

    //根据key获取val
    public V get(K key) {
        //找到位置
        int hash = key.hashCode();//hashCode：给一个哈希值
        int index = hash % array.length;
        Node<K,V> cur = array[index];

        //遍历数组
        while (cur != null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }

}